package com.ls.shiro.realms;

import com.ls.entity.Perm;
import com.ls.entity.Role;
import com.ls.entity.User;
import com.ls.service.UserService;
import com.ls.shiro.salt.MyByteSource;
import com.ls.util.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;

public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份信息
        String principal = (String) authenticationToken.getPrincipal();
        //凭证信息
        authenticationToken.getCredentials();
        //在工厂中获取service对象
        UserService service= (UserService) ApplicationContextUtils.getBean("userService");
        System.out.println(service);
        User user = service.findByUsername(principal);
        System.out.println(user);
        if (!ObjectUtils.isEmpty(user)){
            //return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), new MyByteSource(user.getSalt()),getName());
        }
        return null;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取身份信息
        String principal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("调用授权验证:"+principal);
        //根据主身份信息获取角色和权限信息
        UserService service= (UserService) ApplicationContextUtils.getBean("userService");
        User user = service.findRolesByUsername(principal);
        if(!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            //授权角色
            user.getRoles().forEach(role -> {
                    System.out.println(role.getName());
                    simpleAuthorizationInfo.addRole(role.getName());
                Role r = service.findPermsByRoleId(role.getId());
                List<Perm> perms = r.getPerms();
                perms.forEach(perm -> {
                    System.out.println(perm.getName());
                    simpleAuthorizationInfo.addStringPermission(perm.getName());
                });

            });
            return simpleAuthorizationInfo;
        }
        return null;
    }


}
